<style>
    .inventoryProductDetailForm-title {
        width: 100%;
        margin-left: 20px;
    }

    .inventoryProductDetailForm-title .title, .title {
        display: inline-block;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
        line-height: 19px;
        position: relative;
        padding: 6px 0 19px 0;
    }

    .inventoryProductDetailForm-title .title:after, .title:after {
        content: '';
        display: block;
        position: absolute;
        left: 0;
        bottom: 0;
        width: calc(100% + 6px);
        height: 3px;
        background: #0A8B0A;
    }

</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form">
                <div class="layui-form lay-header">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料类别：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="productTypeId" type="hidden" id="productTypeId1"/>
                                            <div class="layui-input-inline mr0" id="selectProductType"></div>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料名称：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="skuName" id="skuName1" class="layui-input" type="text"
                                                   placeholder="请输入物料名称"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料编码：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="skuCode" id="skuCode1" class="layui-input" type="text"
                                                   placeholder="请输入物料编码"/>
                                        </div>
                                    </div>
                                    <!--<div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料规格：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="skuSpec" id="skuSpec" class="layui-input" type="text"
                                                   placeholder="物料规格"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">仓库：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="warehouseName" id="warehouseName" class="layui-input"
                                                   type="text"
                                                   placeholder="仓库"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">货架：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="warehouseShelfName" id="warehouseShelfName" class="layui-input"
                                                   type="text"
                                                   placeholder="货架"/>
                                        </div>
                                    </div>-->
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">库位编码：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="warehouseShelfSpaceCode" id="warehouseShelfSpaceCode"
                                                   class="layui-input" type="text"
                                                   placeholder="请输入库位编码"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">创建时间：</label>
                                        <div class="layui-input-inline">
                                            <input name="createTime" id="pTime" class="layui-input date-icon" type="text"
                                                   placeholder="请选择创建时间" style="width: 200px" readonly/>
                                        </div>
                                        <input name="startCreateTime" id="sTime" type="hidden"/>
                                        <input name="endCreateTime" id="eTime" type="hidden"/>
                                    </div>
                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <button type="button" class="layui-btn icon-btn color-green"
                                                id="productInventorySearch" lay-filter="productInventorySearch"
                                                lay-submit>查询
                                        </button>
                                        <button type="reset" class="layui-btn icon-btn color-white" lay-filter="resets"
                                                lay-submit>重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="lay-btn-rows">
                        <div class="lay-btn-box">
                            <div class="lay-btn-lt">
                                <button type="button" class="layui-btn icon-btn color-green" id="syncInventory">同步</button>
                                <button id="productBtnExport" type="button" class="layui-btn icon-btn color-green">导出</button>
                            </div>
                            <div class="lay-btn-rt"></div>
                        </div>
                    </div>
                </div>
            </form>
            <table class="layui-table" id="productInventoryTable" lay-filter="productInventoryTable"></table>
        </div>
    </div>
</div>

<script type="text/html" id="inventoryDetailsProductForm">
    <form lay-filter="inventoryDetailsProductForm" class="layui-form model-form">
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: red">*</span>产品编号</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="productCode"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: red">*</span>产品名称</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="productName"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span style="color: red">*</span>物料编码</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="skuCode"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span style="color: red">*</span>物料名称</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="skuName"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span style="color: red">*</span>企业货号</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="enterpriceCode"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: red">*</span>平台供货价</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="supplyPrice"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: red">*</span>市场指导价</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="marketPrice"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: red">*</span>最低活动价</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="activityPrice"/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span style="color: red">*</span>国标条码</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="barcode"/>
                </div>
            </div>
        </div>
        <!--<div class="layui-form-item">
            <label class="layui-form-label" style="width: 100px;"><span style="color: red">*</span>服务商名称</label>
            <div class="layui-form-mid layui-word-aux">
                <span style="color: red" id="name"/>
            </div>
        </div>-->
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;"><span
                        style="color: #ff0000">*</span>录入时间</label>
                <div class="layui-form-mid layui-word-aux">
                    <span style="color: red" id="createTime"/>
                </div>
            </div>
        </div>
    </form>
</script>

<!-- 库存分布 -->
<script type="text/html" id="inventoryDistributeTab">
    <div class="open-form">
        <div class="open-model">
            <div class="open-auto" style="padding-top: 5px;">
                <table class="layui-table" id="inventoryDistributeTable" lay-filter="inventoryDistributeTable"></table>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            </div>
        </div>
    </div>
</script>

<script type="text/html" id="inventoryDetailDistributeTab">
    <div class="open-form">
        <div class="open-model">
            <div class="open-auto" style="padding-top: 5px;">
                <table class="layui-table" id="inventoryDetailDistributeTable" lay-filter="inventoryDistributeTable"></table>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            </div>
        </div>
    </div>
</script>





<!-- 库存明细 -->
<script type="text/html" id="repertoryDetailsTab">
    <div class="layui-fluid">
        <table class="layui-table" id="warehouseDetailsTable" lay-filter="warehouseDetailsTable"></table>
        <br>
        <span>库存明细</span>
        <table class="layui-table" id="repertoryDetailsTable" lay-filter="repertoryDetailsTable"></table>
    </div>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="productInventoryTableBar">
    <a class="layui-btn layui-btn layui-btn-xs" lay-event="inventoryDistribution">库存分布</a>
</script>

<script type="text/html" id="inventoryDistributeTableBar">
    <a class="layui-btn layui-btn layui-btn-xs" lay-event="inventoryDistributeDistribution">料箱明细</a>
</script>

<script type="text/javascript" src="../../../admin/assets/js/jsencrypt.min.js"></script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var unitName;

        //物料类别
        var useSelect = admin.initDataSelectTree(true, 'enterprise/product/admin/productType/getAllTreeData', {limit: 99999}, "selectProductType", null, "物料类别", "productTypeId", function (row) {
            //取消选择时 清空物料类别ID
            if (row.arr.length == 0) {
                $("input[name='productTypeId']").val('');
            }
        });

        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value) {
                    var dateValue = value.split(" - ");
                    $("#sTime").val(dateValue[0] + " 00:00:00");
                    $("#eTime").val(dateValue[1] + " 23:59:59");
                } else {
                    $("#sTime").val();
                    $("#eTime").val();
                }
            }
        });
        
        // 渲染表格
        var insTb = table.render({
            elem: '#productInventoryTable',
            url: config.base + 'enterprise/storage/admin/productInventory/list',
            page: true,
            limit: 10,
            // limits: [5, 10, 20, 30, 40, 50, 60, 70, 80],
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: "序号", width: 60}
                , {field: 'skuName', align: 'center', title: '物料名称'}
                , {field: 'skuCode', align: 'center', title: '物料编码'}
                , {field: 'skuSpec', align: 'center', title: '物料规格'}
                , {field: 'productTypeName', align: 'center', title: '物料类别'}
                , {field: 'warehouseShelfSpaceCode', align: 'center', title: '库位编码'}
                , {field: 'quantity', align: 'center', title: '库存'}
                , {field: 'createTime', align: 'center', title: '创建时间', width: 160}
                , {align: 'center', toolbar: '#productInventoryTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
            }
        });
        form.render('select');

        // 工具条点击事件
        table.on('tool(productInventoryTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'inventoryDistribution') { //库存分布
                showInventoryDistributeModel(data);
            }
        });
        // 工具条点击事件
        table.on('tool(inventoryDistributeTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'inventoryDistributeDistribution') { //库存分布
                showInventoryDetailDistributeModel(data);
            }
        });
        // 搜索
        form.on('submit(productInventorySearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
            return false;
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-query-box").find('select').val("");
            $(".lay-query-box").find('input').val("");
            xmSelect.get('#selectProductType')[0].setValue([])
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });
        $('#syncInventory').click(function () {
            layer.load(2);
            admin.req(
                'enterprise/storage/admin/productInventory/sync',
                {},
                function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1 });
                        insTb.reload('productInventoryTable');
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                },
                'GET'
            );
        });
        // 显示库存分布弹窗
        function showInventoryDistributeModel(data) {
            admin.open({
                type: 1,
                area: ['1500px', '80%'],
                offset: '100px',
                title: '库存分布',
                content: $('#inventoryDistributeTab').html(),
                success: function () {
                    table.render({
                        elem: '#inventoryDistributeTable',
                        data: data.productInventoryDetailList,
                        cols: [[
                              {type: 'numbers', title: "序号", width: 60}
                            , {field: 'warehouseShelfSpaceCode', align: 'center', title: '库位'}
                            , {field: 'warehouseTypeName', align: 'center', title: '仓库类型', width: 150}
                            , {field: 'warehouseName', align: 'center', title: '仓库'}
                            , {field: 'warehouseAreaName', align: 'center', title: '库区', width: 150}
                        /*    , {field: 'warehouseShelfName', align: 'center', title: '货架', width: 160}*/
                            , {field: 'palletBoxCode', align: 'center', title: '料箱'}
                            , {field: 'quantity', align: 'center', title: '数量'}
                            , {align: 'center', toolbar: '#inventoryDistributeTableBar', title: '操作', width: 200}
                        ]],
                    });
                }
            })
        }


        // 料箱明细数据
        function showInventoryDetailDistributeModel(data) {
            let warehouseShelfSpaceId = data.warehouseShelfSpaceId;
            admin.open({
                type: 1,
                area: ['1200px', '70%'],
                offset: '100px',
                title: '料箱明细',
                content: $('#inventoryDetailDistributeTab').html(),
                success: function () {
                    // 初始化表格实例（只执行一次）
                    table.render({
                        elem: '#inventoryDetailDistributeTable',
                        url: config.base + 'enterprise/palletBoxSkuIterm/admin/palletBoxSkuIterm/list',
                        page: true,
                        limit: 10,
                        limits: [5, 10, 20, 30, 40, 50, 60, 70, 80],
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: "序号", width: 60},
                            {field: 'skuName', align: 'center', title: '物料名称'},
                            {field: 'skuCode', align: 'center', title: '物料编码'},
                            {field: 'num', align: 'center', title: '数量'},
                            {field: 'warehouseName', align: 'center', title: '仓库'},
                            {field: 'warehouseAreaName', align: 'center', title: '库区'},
                            {field: 'shelfName', align: 'center', title: '货架'},
                            {field: 'shelfSpaceName', align: 'center', title: '库位'},
                            {field: 'shelfSpaceCode', align: 'center', title: '库位编码'},
                            {field: 'palletBoxCode', align: 'center', title: '料箱编号'}
                        ]],
                        done: function (res, curr, count) {
                            // 表格渲染完成后的回调函数
                            if (!res || !res.data || res.data.length === 0) {
                                debugger;
                                // 如果没有数据，直接在前端清空表格内容而不重新加载
                                var tableElement = table.cache['inventoryDetailDistributeTable'];
                                if(tableElement && tableElement.data){
                                    tableElement.data = []; // 清空数据
                                    table.reload('inventoryDetailDistributeTable'); // 仅刷新表格视图
                                }
                            }
                        }
                    });

                    // 使用 table.reload 来更新表格数据和查询参数，只在初始化时调用一次
                    table.reload('inventoryDetailDistributeTable', {
                        where: {
                            warehouseShelfSpaceId: warehouseShelfSpaceId // 将 warehouseShelfSpaceId 作为查询参数传递
                        },
                        page: {
                            curr: 1 // 返回第一页
                        }
                    });
                }
            });
        }

   /*     $('#productBtnExport').click(function () {
            var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
            var crypt = new JSEncrypt();
            crypt.setKey(publicKey);
            var token = "Bearer "+config.getToken();
            var tokenLeft = token.substring(0,50);
            var tokenRight = token.substring(50);
            var enc = crypt.encrypt(tokenLeft);
            var access_token = enc+tokenRight;
            access_token = access_token.replaceAll('+', '%2B');
            let skuName = $('#skuName').val();
            let productTypeId = $('#productTypeId').val();
            let skuCode= $('#skuCode').val();
           // window.location.href = config.base + 'enterprise/storage/admin/productInventory/export?skuName=' + skuName + '&productTypeId=' + productTypeId+ '&skuCode=' + skuCode+ '&access_token='+ access_token;
            window.location.href =config.base + 'enterprise/storage/admin/productInventory/export?+access_token='+ access_token;

        });*/
        // 监听回车键查询
        $(document).on('keydown', function (event) {
            event.stopPropagation();
            if (event.keyCode === 13) {
                $('#productInventorySearch').click();
            }
        });


        $('#productBtnExport').click(function () {
            
            let skuName = $('#skuName1').val();
            let productTypeId = $('#productTypeId1').val();
            let skuCode = $('#skuCode1').val();

            // 创建一个对象来保存所有可能的查询参数
            let queryParams = {
                skuName: skuName,
                productTypeId: productTypeId,
                skuCode: skuCode
            };

            // 过滤掉值为 undefined 的属性
            queryParams = Object.keys(queryParams)
                .filter(key => queryParams[key] !== undefined && queryParams[key] !== '')
                .reduce((obj, key) => {
                    obj[key] = queryParams[key];
                    return obj;
                }, {});

            // 将过滤后的参数对象转换为查询字符串
            let queryString = new URLSearchParams(queryParams).toString();

            // 获取当前日期和时间
            let now = new Date();
            let year = now.getFullYear();
            let month = String(now.getMonth() + 1).padStart(2, '0'); // 注意：getMonth() 返回值是 0-11
            let day = String(now.getDate()).padStart(2, '0');
            let hour = String(now.getHours()).padStart(2, '0');
            let minute = String(now.getMinutes()).padStart(2, '0');
            let second = String(now.getSeconds()).padStart(2, '0');

            // 格式化日期和时间为 YYYYMMDD_HHMMSS 形式
            let formattedDateTime = `${year}${month}${day}_${hour}${minute}${second}`;

            // 设置下载文件名为 "产品数据_YYYYMMDD_HHMMSS.xls"
            let fileName = `产品数据_${formattedDateTime}.xls`;

            // 创建完整的URL，包括查询参数和文件名作为额外参数（如果后端支持的话）
            let fullUrl = config.base + 'enterprise/storage/admin/productInventory/export?' + queryString + '&fileName=' + encodeURIComponent(fileName);

            // 使用 window.open 打开新页面进行下载
            window.open(fullUrl + '&Authorization=Bearer ' + encodeURIComponent(config.getToken()), '_blank');
           // 注意：这里假设后端能够处理 fileName 参数，并根据它设置响应头中的 Content-Disposition 来指定下载文件名。
            // 如果后端不支持通过 URL 参数指定文件名，你可能需要调整后端代码来接受这种请求方式。
        });


    });
</script>